package com.tornado.community.interceptor;

import com.tornado.community.model.User;
import com.tornado.community.provider.Tools;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SessionInterceptor implements HandlerInterceptor {
    private final Tools tools;

    public SessionInterceptor(Tools tools) {
        this.tools = tools;
    }

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) throws IOException {
        User user = tools.loginCheck(request);
        if (user == null) {
            response.sendRedirect("/");
            return false;
        } else {
            return true;
        }
    }
}
